package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/*
 线程任务
 负责与特定的客服端进行HTTP交互
 */
public class ClientHandler implements Runnable{//实现了接口要重写他的方法
    //提升作用域
    private Socket socket;

    //构造方法，初始化
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        //http://localhost:8088/
        try {
            //1.1解析请求
            String line = readLine();

            System.out.println("读取到的请求行是："+line);//客服端发来的请求
            String method;//请求的方式
            String uri;//请求的抽象路径
            String protocol;//请求协议版本号
            //解析请求相关信息
            String[] data = line.split("\\s");
            method = data[0];
            uri = data[1];
            protocol = data[2];
            System.out.println("请求方式："+method);
            System.out.println("请求路径："+uri);
            System.out.println("版本号："+protocol);

            //1.2读取消息头




            //2处理请求
            //3发送响应

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //响应候断开连接
                socket.close();
            } catch (IOException e) {
                System.out.println("关闭流异常！");
            }
        }

    }

    public String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';//保存本次读取到的字符
        char pre = 'a';//本次读取到的字符
        int d;
        while ((d=in.read()) != -1){
            cur = (char) d;
            if (pre==13 && cur==10){//判断是否连续读取到了回车+换行
                break;
            }
            builder.append(cur);
            pre = cur;//下次循环前将本次读取到的字符记为上次读取的字符
        }
        return builder.toString().trim();
    }
}
